import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { UserInfo } from '../types/login';

interface AuthState {
  isAuthenticated: boolean;
  user: UserInfo | null;
  token: string | null;
  refreshToken: string | null;
  expireIn: number | null;
  login: (userData: {
    username: string;
    phone: string;
    nickname: string;
    logo: string;
    email: string;
    id: number;
    token: string;
    refreshToken: string;
    expireIn: number;
  }) => void;
  logout: () => void;
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set) => ({
      isAuthenticated: false,
      user: null,
      token: null,
      refreshToken: null,
      expireIn: null,
      login: (userData) => set({ 
        isAuthenticated: true, 
        user: {
          username: userData.username,
          phone: userData.phone,
          nickname: userData.nickname,
          logo: userData.logo,
          id: userData.id,
          email: userData.email
        },
        token: userData.token,
        refreshToken: userData.refreshToken || null, // Handle empty refreshToken
        expireIn: userData.expireIn
      }),
      logout: () => {
        localStorage.removeItem('token');
        set({ isAuthenticated: false, user: null, token: null, refreshToken: null, expireIn: null });
      },
    }),
    {
      name: 'auth-storage',
    }
  )
);